/**
 * 
 */
package com.hexacta.hrs.repositories.impl;

import java.util.Collection;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.hexacta.hrs.timeoff.CompensationDaysAssignation;

/**
 * @author mfunes
 * 
 */
public class CompensationDaysRecordObjectRepository extends
        HibernateRecordObjectRepository<CompensationDaysAssignation> {

    /** {@inheritDoc} */
    public CompensationDaysRecordObjectRepository(final Class<CompensationDaysAssignation> entityClass) {
        super(entityClass);
    }

    /** {@inheritDoc} */
    @SuppressWarnings("unchecked")
    @Override
    public Collection<CompensationDaysAssignation> matching(final CompensationDaysAssignation criteria) {
        if (criteria.getAssignedTo() == null && criteria.getAssignedBy() == null && criteria.getDateAssigned() == null
                && (criteria.getNotes() == null || StringUtils.isEmpty(criteria.getNotes())))
            return super.matching(criteria);

        Criteria crit = getSession().createCriteria(CompensationDaysAssignation.class);

        if (criteria.getAssignedTo() != null) {
            Example exampleEmployee = Example.create(criteria.getAssignedTo()).ignoreCase().enableLike(
                    MatchMode.ANYWHERE);
            crit.createCriteria("assignedTo").add(exampleEmployee);
        }

        if (criteria.getAssignedBy() != null) {
            Example exampleAssignedBy = Example.create(criteria.getAssignedBy()).ignoreCase().enableLike(
                    MatchMode.ANYWHERE);
            crit.createCriteria("assignedBy").add(exampleAssignedBy);
        }

        if (criteria.getDateAssigned() != null && criteria.getNotes() != null) {
            Date criteriaFrom = criteria.getDateAssigned();
            Long longTo = 0L;
            Boolean error = false;

            try {
                longTo = Long.parseLong(criteria.getNotes());
            } catch (NumberFormatException e) {
                // Nada
                error = true;
            }

            if (!error) {
                Date criteriaTo = new Date(longTo);
                crit.add(Restrictions.between("dateAssigned", criteriaFrom, criteriaTo));
            }
        }
        criteria.setDateAssigned(null);
        criteria.setNotes(null);
        Example exampleTimeOff = Example.create(criteria).ignoreCase().enableLike(MatchMode.ANYWHERE);
        crit.add(exampleTimeOff);

        return crit.list();
    }
}
